from django_redis import get_redis_connection
from meiduo_mall.utils import meiduo_json


def merge_cookie_to_redis(request, user, response):
    # 读取cookie中的购物车数据，保存到redis中
    # 1.读取cookie中的购物车数据
    cart_str = request.COOKIES.get('cart')
    if cart_str is None:
        return response
    cart_dict = meiduo_json.loads(cart_str)

    # 2.保存到redis
    redis_cli = get_redis_connection('cart')
    redis_pipeline = redis_cli.pipeline()
    hash_key = 'cart_%d' % user.id
    set_key = 'cart_selected_%d' % user.id
    for sku_id, sku_dict in cart_dict.items():
        # hash
        redis_pipeline.hset(hash_key, sku_id, sku_dict.get('count'))
        # set
        if sku_dict.get('selected'):
            redis_pipeline.sadd(set_key, sku_id)
        else:
            redis_pipeline.srem(set_key, sku_id)
    redis_pipeline.execute()

    # 3.删除cookie中购物车数据
    response.set_cookie('cart', '', max_age=0)
    return response
